package com.muqi.app.im.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.easeui.widget.EaseAlertDialog;
import com.muqi.app.im.adapter.SearchFriendsAdapter;
import com.muqi.app.im.qmain.EMHelper;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.modles.PersonBean;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog;
import com.wenhui.pedant.SweetAlert.SweetAlertDialog.OnSweetClickListener;

public class AddFriendsActivity extends BaseFragmentActivity implements OnEditorActionListener,
	OnItemClickListener, SearchFriendsAdapter.AddFriendsListener {
	private EditText find_input;
	private ListView searchListView;
	private List<PersonBean> resultList = new ArrayList<PersonBean>();
	private SearchFriendsAdapter mAdapter = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_add_friends);
	}
	
	@Override
	protected void onInit() {
		find_input = (EditText)findViewById(R.id.find_friends_input);
		find_input.setOnEditorActionListener(this);
		searchListView = (ListView)findViewById(R.id.search_list_view);
		searchListView.setOnItemClickListener(this);
	}

	@Override
	protected void onData() {
		
	}
	
	public void onSearch(View v){
		if(TextUtils.isEmpty(find_input.getText().toString())){
			find_input.setError("内容不能为空");
		}else{
			searchingFriends(find_input.getText().toString());
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			if(TextUtils.isEmpty(find_input.getText().toString())){
				find_input.setError("内容不能为空");
			}else{
				searchingFriends(find_input.getText().toString());
			}
			return true;
		}
		return false;
	}
	
	private void searchingFriends(final String nickName){
		if(NetWorkUtils.isNetworkAvailable(this)){
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("token", mSpUtil.getToken());
			map.put("str", nickName);
			String requestApi = ParamsUtils.buildParams(NetWorkApi.SEARCH_FRIENDS_API, map);
			MyAsyncHttp.get(this, requestApi, new AsyncCallBackListener() {
				
				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode, String request, String result) {
					if(resuleCode == RESULTCODE.SUCCESS){
						try {
							JSONObject resultJSON = new JSONObject(result);
							resultList.clear();
							JSONArray dataArray = resultJSON.getJSONArray("data");
							for(int i=0;i<dataArray.length();i++){
								PersonBean item = PersonBean.fromJson(dataArray.optJSONObject(i));
								if(item!=null) resultList.add(item);
							}
							if(resultList!=null && resultList.size()>0){
								showSearchResultView();
							}else{
								ShowToast.showShort(mContext, "未找到相关信息");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}else{
			ShowToast.showShort(this, R.string.net_break);
		}
	}
	
	private void showSearchResultView(){
		if(mAdapter!=null) mAdapter = null;
		mAdapter = new SearchFriendsAdapter(this, resultList, this);
		searchListView.setAdapter(mAdapter);
	}
	
	/**
	 *  添加contact
	 * @param view
	 */
	public void addContact(final String toAddUsername){
		
		if(EMChatManager.getInstance().getCurrentUser().equals(toAddUsername)){
			new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
			.setTitleText("不能添加自己")
			.setConfirmText("确定")
			.showCancelButton(false)
			.setConfirmClickListener(new OnSweetClickListener() {
				@Override
				public void onClick(SweetAlertDialog mDialog) {
					mDialog.dismissWithAnimation();
				}
			}).show();
			return;
		}
		if(EMHelper.getInstance().getContactList().containsKey(toAddUsername)){
		    //提示已在好友列表中(在黑名单列表里)，无需添加
		    if(EMContactManager.getInstance().getBlackListUsernames().contains(toAddUsername)){
		        new EaseAlertDialog(this, "黑名单好友，无需添加").show();
		        return;
		    }
			new EaseAlertDialog(this, R.string.This_user_is_already_your_friend).show();
			return;
		}
		new Thread(new Runnable() {
			public void run() {
				try {
					//demo写死了个reason，实际应该让用户手动填入
					EMContactManager.getInstance().addContact(toAddUsername, "加个好友呗");
					runOnUiThread(new Runnable() {
						public void run() {
							ShowToast.showShort(mContext, "好友申请已发送成功");
						}
					});
				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {
							
						}
					});
				}
			}
		}).start();
	}

	public void onBack(View v){
		finish();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onAddThisFriend(int position) {
		addContact(resultList.get(position).im_user_id);
	}
}
